package com.example.myapplication;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    private AppCompatEditText et_nickname = null;
    private AppCompatEditText et_password = null;
    private AppCompatButton loginButton =null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_nickname = findViewById(R.id.et_nickname);
        et_password = findViewById(R.id.et_password);
        loginButton = findViewById(R.id.loginButton);

        loginButton.setOnClickListener(view->{
            HttpParams httpParams = new HttpParams();
            httpParams.put("mobile",et_nickname.getText().toString());
            httpParams.put("password",et_password.getText().toString());
            OkGo.<String>post(Common.API_URL + "base/login/").tag(this).params(httpParams).execute(new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    String data = response.body();
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        String code = jsonObject.getString("code");
                        if (!code.equals("1")){
                            String msg = jsonObject.getString("msg");
                            Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String token = jsonObject.getString("data");
                        MainActivity.editor.putString("token", token).apply();
                        Toast.makeText(LoginActivity.this, "登录成功~", Toast.LENGTH_SHORT).show();
                        MainActivity.isLogin = true;
                        finish();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    }

                });
            });

    }
}
